package service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import dao.EntityContext;

import util.MD5Util;
import entity.ExamInfo;
import entity.Question;
import entity.QuestionInfo;
import entity.User;
import exception.ExamNotFinishException;
import exception.NameOrPasswordException;

public class ExamServiceImpl implements ExamService {
	/**取得数据存放类*/
	private EntityContext context;
	/**成绩**/
	private int score = 0;
	/**考生*/
	private User user;
	/** 考卷, 是试题信息的集合 */
	public List<QuestionInfo> paper = new ArrayList<QuestionInfo>();
	/**
	 * 考试业务类的构造方法，传入EntityContext，以从EntityContext中取得各种数据
	 * @param context
	 */
	public ExamServiceImpl(EntityContext context) {
		this.context = context;
	}
	
	// TODO day03 登录业务处理
	
	@Override
	public User login(int id, String pwd) throws NameOrPasswordException {
		User u = context.getUser(id);
		if (u == null) {
			throw new NameOrPasswordException();
		}
		if (u.getPassword().equals(MD5Util.md5(pwd))) {
			user = u;
			return u;
		}
		throw new NameOrPasswordException();
	}

	@Override
	public ExamInfo start() {
		// 随机组织考题
		buildPaper();
		// 创建这场考试的信息对象ExamInfo
		ExamInfo info = new ExamInfo();
		info.setQuestionCount(paper.size());
		info.setTimeLimit(context.getTimeLimit());
		info.setTitle(context.getPaperTitle());
		info.setUser(user);
		return info;
	}

	private void buildPaper() {
		Random random = new Random();
		int i = 0;
		for (int level = Question.LEVEL1; level <= Question.LEVEL10; level++) {
			List<Question> list = context.getQuestions(level);
			Question q1 = list.remove(random.nextInt(list.size()));
			Question q2 = list.remove(random.nextInt(list.size()));
			paper.add(new QuestionInfo(i++, q1));
			paper.add(new QuestionInfo(i++, q2));
		}
	}

	@Override
	public void sendAnswers(int questionIndex, List<Integer> answer) {
		System.out.println("answer:"+answer);
		QuestionInfo qInfo = paper.get(questionIndex);
		System.out.println("q:"+qInfo);
		qInfo.setUserAnswers(new ArrayList<Integer>(answer));
	}

	@Override
	public int commit() {
		// 计算考试分数的过程
		for (QuestionInfo q : paper) {
			List<Integer> userAnswer = q.getUserAnswers();
			if (userAnswer.equals(q.getQuestion().getAnswer())) {
				score += q.getQuestion().getScore();
			}
		}
		return score;
	}

	@Override
	public QuestionInfo getQuestion(int index) {
		return paper.get(index);
	}

	@Override
	public int result() throws ExamNotFinishException {
		return score;
	}
	public String getRule(){
		List<String> rules=context.getRules();
		StringBuilder sb=new StringBuilder();
		for(String s:rules){
			sb.append(s+"\n");
		}
		return sb.toString();
	}
}
